package com.letv.core.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.letv.core.bean.DownloadDBListBean;
import com.letv.core.bean.DownloadDBListBean.DownloadDBBean;
import com.letv.core.constant.DatabaseConstant;
import com.letv.core.utils.DownloadUtils;
import com.letv.core.utils.LetvTools;
import com.letv.core.utils.LogInfo;
import com.letv.core.utils.StoreUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;


public class WorldCupTraceHandler {
    private Context context;

    public WorldCupTraceHandler(Context context) {
        this.context = context;
    }

    /**
     * 根据下载任务状态获取下载记录数量
     * 
     * @param status
     * @return
     */
    public int getWorldCupTraceNumByStatus(int status) {
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_WORLDCUPTRACE,
                    null, DatabaseConstant.WorldCupTrace.Field.FINISH + "=?",
                new String[] { status+"" },
                DatabaseConstant.WorldCupTrace.Field.TIMESTAMP + " ASC");
            return cursor.getCount();
        } finally {
            LetvTools.closeCursor(cursor);
        }
    }
    
    /**
     * 根据下载任务状态获取除该状态下载记录数量
     * 
     * @param status
     * @return
     */
//    public int getWorldCupTraceNumExceptStatus(int status) {
//        Cursor cursor = null;
//        try {
//            cursor = context.getContentResolver().query(LetvContentProvider.URI_WORLDCUPTRACE,
//                    null, DatabaseConstant.WorldCupTrace.Field.FINISH + "!=?",
//                new String[] { status+"" },
//                DatabaseConstant.WorldCupTrace.Field.TIMESTAMP + " ASC");
//            return cursor.getCount();
//        } finally {
//            LetvTools.closeCursor(cursor);
//        }
//    }

    /**
     * 获取正在下载列表
     * 
     * @return DownloadDBListBean
     */
//    public DownloadDBListBean getLoadingDownloadInfo() {
//        DownloadDBListBean list = new DownloadDBListBean();
//
//        boolean flag = false;
//
//        Cursor cursor= null;
//
//        try {
//            cursor = context.getContentResolver().query(LetvContentProvider.URI_WORLDCUPTRACE,
//                    null, DatabaseConstant.WorldCupTrace.Field.FINISH + "<>?",
//                    new String[]{"4"}, DatabaseConstant.WorldCupTrace.Field.TIMESTAMP + " ASC");
//            boolean hasUpdateMulti = PreferencesManager.getInstance().hasUpdateMulti();
//            if (!hasUpdateMulti) {
//                if (cursor != null && cursor.getCount() > 0) {
//                    while (cursor.moveToNext()) {
//                        int episodeId = cursor.getInt(cursor
//                                .getColumnIndex(DatabaseConstant.WorldCupTrace.Field.EPISODE_ID));
//                        // 比对下载表，下载包实现has方法
//                        boolean isExist = DownloadManager.getInstance(context).isDownloadExist(
//                                episodeId + "");
//                        if (!isExist) {
//                            delete(episodeId);
//                            flag = true;
//                        }
//                    }
//                }
//                PreferencesManager.getInstance().updateMulti();
//            }
//
//            if (flag) {
//                cursor = context.getContentResolver().query(LetvContentProvider.URI_WORLDCUPTRACE,
//                        null, DatabaseConstant.WorldCupTrace.Field.FINISH + "<>?",
//                        new String[]{"4"},
//                        DatabaseConstant.WorldCupTrace.Field.TIMESTAMP + " ASC");
//            } else {
//                cursor.moveToPosition(-1);
//            }
//
//            while (cursor.moveToNext()) {
//                list.add(createDownloadDBBean(cursor));
//            }
//
//        }catch(Exception e) {
//
//            e.printStackTrace();
//        }finally {
//
//            if(cursor!= null&& !cursor.isClosed()) {
//
//                cursor.close();
//            }
//        }
//        return list;
//
//    }
    
    /**
     * 获取未完成列表，除了状态为已完成的列表
     * @return
     */
    public DownloadDBListBean getDownloadExceptFinishTrace() {
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_WORLDCUPTRACE,
                    null, DatabaseConstant.WorldCupTrace.Field.FINISH + "!=?",
                    new String[] { "4" },
                    DatabaseConstant.WorldCupTrace.Field.TIMESTAMP + " ASC");

            DownloadDBListBean arrayList = new DownloadDBListBean();

            while (cursor.moveToNext()) {
                arrayList.add(createDownloadDBBean(cursor));
            }

            return arrayList;
        } finally {
            LetvTools.closeCursor(cursor);
        }
    }

    /**
     * 获取所有已下载完成的数据
     * 
     * @return DownloadDBListBean
     */
    public DownloadDBListBean getAllFinishTrace() {
        Cursor cursor = null;
        ArrayList<Integer> deList = new ArrayList<Integer>();
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_WORLDCUPTRACE,
                    null, DatabaseConstant.WorldCupTrace.Field.FINISH + "=?",
                    new String[] { "4" },
                    DatabaseConstant.WorldCupTrace.Field.TIMESTAMP + " DESC");

            DownloadDBListBean arrayList = new DownloadDBListBean();

            while (cursor != null && cursor.moveToNext()) {
                DownloadDBBean mDownloadDBBean = createDownloadDBBean(cursor);
                if(isFileExist(mDownloadDBBean.getVid())){
                    arrayList.add(mDownloadDBBean);
                    LogInfo.log("ljnalex", "checkFileExist exist");
                } else {
                    LogInfo.log("ljnalex", "checkFileExist not exist");
                    deList.add(mDownloadDBBean.getVid());
                }
            }
            for (int i = 0; i < deList.size(); i++) {
                delete(deList.get(i));
            }
            return arrayList;
        } finally {
            LetvTools.closeCursor(cursor);
        }
    }
    /**
     * 检测文件是否存在
     * @param episodeId
     * @return
     */
    public boolean isFileExist(int episodeId) {
        File file = getDownloadFileByEpisodeId(episodeId);
        return file != null && file.exists();
    }

    /**
     *  通过视频id获取文件
     * @param episodeid 剧集id
     * @return
     */

    public File getDownloadFileByEpisodeId(long episodeid) {
        if (!StoreUtils.isSdcardAvailable()) {
            return null;
        }

        File downloadDir = null;
        DownloadDBBean info = getInFinish(episodeid);
        if (info != null && info.getFilePath() != null) {
            downloadDir = new File(info.getFilePath());
        }

        File downloadFile = new File(downloadDir, DownloadUtils.createFileName(episodeid));

        return downloadFile;
    }
    
    /**
     * 获取某一专辑Id下所有已完成的数据
     * @param albumId
     * @return
     */
    public DownloadDBListBean getAllFinishTraceByAlbumId(String albumId) {
        DownloadDBListBean mDownloadDBBeanList = new DownloadDBListBean();
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_WORLDCUPTRACE,
                    null, DatabaseConstant.WorldCupTrace.Field.ALBUM_ID + "=? AND "
                            + DatabaseConstant.WorldCupTrace.Field.FINISH + "=?",
                    new String[] { albumId + "", "4" },
                    DatabaseConstant.WorldCupTrace.Field.ORDER + " ASC");
            while (cursor.moveToNext()) {
                mDownloadDBBeanList.add(createDownloadDBBean(cursor));
            }
            return mDownloadDBBeanList;
        } finally {
            LetvTools.closeCursor(cursor);
        }
    }

    /**
     * 获取所有的下载记录
     * 
     * @return
     */
    public DownloadDBListBean getAllDownLoadTrace() {
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_WORLDCUPTRACE,
                    null, null, null, DatabaseConstant.WorldCupTrace.Field.TIMESTAMP + " ASC");

            DownloadDBListBean arrayList = new DownloadDBListBean();
            while (cursor != null && cursor.moveToNext()) {
                arrayList.add(createDownloadDBBean(cursor));
            }
            return arrayList;
        } finally {
            LetvTools.closeCursor(cursor); 
        }
    }

    public DownloadDBBean getDownloadDBBeanPosition(int position) {
        Cursor cursor = null;
        DownloadDBBean mDownloadDBBean = null;
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_WORLDCUPTRACE,
                    null, DatabaseConstant.WorldCupTrace.Field.FINISH + "<>?",
                    new String[] { "4" },
                    DatabaseConstant.WorldCupTrace.Field.TIMESTAMP + " ASC");
            if (cursor.move(position + 1)) {
                mDownloadDBBean = createDownloadDBBean(cursor);
            }
            return mDownloadDBBean;
        } finally {
            LetvTools.closeCursor(cursor);
        }
    }

    /**
     * 是否存在本条记录
     * 
     * @param episodeId
     * @return 存在记录的视频标题
     */
    public DownloadDBBean has(long episodeId) {
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_WORLDCUPTRACE,
                    null,
                    DatabaseConstant.WorldCupTrace.Field.EPISODE_ID + "=?",
                    new String[] { episodeId + "" }, null);

            if (cursor.moveToFirst()) {
                return createDownloadDBBean(cursor);
            } else {
                return null;
            }
        } finally {
            LetvTools.closeCursor(cursor);
        }
    }

    /**
     * 获取下载表中所有的EpisodeId
     * 
     * @return
     */
    public List<Integer> getAllDownloadEpisodeId() {
        List<Integer> ids = new ArrayList<Integer>();
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_WORLDCUPTRACE,
                    new String[] { DatabaseConstant.WorldCupTrace.Field.EPISODE_ID }, null,
                    null, null);
            while (cursor.moveToNext()) {
                int id = cursor.getInt(cursor
                        .getColumnIndex(DatabaseConstant.WorldCupTrace.Field.EPISODE_ID));
                ids.add(id);
            }
        } finally {
            LetvTools.closeCursor(cursor);
        }
        return ids;
    }

    /**
     * 查询所有的专辑ID，去重复
     * 
     * @return
     */
    public List<Long> getAllDownloadAlbumId() {
        List<Long> albumIds = null;
        Cursor cursor = null;
        try {
            String selection = 1 + " = " + 1 + " group by "
                    + DatabaseConstant.WorldCupTrace.Field.ALBUM_ID;
            cursor = context.getContentResolver().query(LetvContentProvider.URI_WORLDCUPTRACE,
                    new String[] { DatabaseConstant.WorldCupTrace.Field.ALBUM_ID }, selection,
                    null, DatabaseConstant.WorldCupTrace.Field.TIMESTAMP + " ASC");
            albumIds = new ArrayList<Long>();
            while (cursor.moveToNext()) {
                long id = cursor.getLong(cursor
                        .getColumnIndex(DatabaseConstant.WorldCupTrace.Field.ALBUM_ID));
                albumIds.add(id);
            }
        } finally {
            LetvTools.closeCursor(cursor);
        }
        return albumIds;
    }

    /**
     * 获取所有的下载信息 根据专辑ID分组
     * 
     * @return
     */
    public LinkedHashMap<String, List<DownloadDBBean>> getAllDownLoadItems() {
        LinkedHashMap<String, List<DownloadDBBean>> mAllDownLoadItemsMap = null;
        List<DownloadDBBean> mDownloadDBBeanList = null;
        try {
            List<Long> albumIds = getAllDownloadAlbumId();
            DownloadDBListBean allDownLoadTrace = getAllDownLoadTrace();
            mAllDownLoadItemsMap = new LinkedHashMap<String, List<DownloadDBBean>>();
            if (albumIds != null && albumIds.size() > 0) {
                if (allDownLoadTrace != null && allDownLoadTrace.size() > 0) {
                    for (Long albumId : albumIds) {
                        LogInfo.log("debug_tag", "---albumId =" + albumId);
                        mDownloadDBBeanList = new ArrayList<DownloadDBBean>();
                        for (DownloadDBBean downloadDBBean : allDownLoadTrace) {
                            if (downloadDBBean.getAid() == albumId.longValue()) {
                                mDownloadDBBeanList.add(downloadDBBean);
                                LogInfo.log("debug_tag", "---albumId =" + albumId
                                        + " downloadDBBean=" + downloadDBBean.toString());
                            }
                        }
                        LogInfo.log("debug_tag", "---mDownloadDBBeanList.size()="
                                + mDownloadDBBeanList.size());
                        if (mDownloadDBBeanList.size() > 0) {
                            mAllDownLoadItemsMap.put(albumId + "", mDownloadDBBeanList);
                        }
                    }
                }
            }
        } finally {
        }
        return mAllDownLoadItemsMap;
    }

    /**
     * 根据albumId与order获取已下载信息
     * 
     * @param albumId
     * @param order
     * @return 存在记录的视频标题
     */
    public DownloadDBBean getTitleInFinish(int albumId, float order) {
        synchronized (context) {
            Cursor cursor = null;
            try {
                DownloadDBBean mDownloadDBBean = null;
                cursor = context.getContentResolver().query(
                        LetvContentProvider.URI_WORLDCUPTRACE,
                        null,
                        DatabaseConstant.WorldCupTrace.Field.ALBUM_ID + "=? AND "
                                + DatabaseConstant.WorldCupTrace.Field.ORDER + "=? AND "
                                + DatabaseConstant.WorldCupTrace.Field.FINISH + "=?",
                                new String[] { albumId + "", order + "", "4" }, null);
                if (cursor.moveToFirst()) {
                    mDownloadDBBean = createDownloadDBBean(cursor);
                }
                return mDownloadDBBean;
            } finally {
                LetvTools.closeCursor(cursor);
            }
        }
    }

    /**
     * 根据视频ID 获取已下载信息
     * 
     * @param episodeId
     * @return
     */
    public DownloadDBBean getInFinish(long episodeId) {
        synchronized (context) {
            Cursor cursor = null;
            try {
                DownloadDBBean mDownloadDBBean = null;
                cursor = context.getContentResolver().query(
                        LetvContentProvider.URI_WORLDCUPTRACE,
                        null,
                        DatabaseConstant.WorldCupTrace.Field.EPISODE_ID + "=? AND "
                                + DatabaseConstant.WorldCupTrace.Field.FINISH + "=?",
                                new String[] { episodeId + "", "4" }, null);
                if (cursor!= null && cursor.moveToFirst()) {
                    mDownloadDBBean = createDownloadDBBean(cursor);
                }
                return mDownloadDBBean;
            } finally {
                LetvTools.closeCursor(cursor);
            }
        }
    }

    /**
     * 根据albumId与vid获取已下载信息
     * 
     * @param albumId
     * @param vid
     * @return 存在记录的视频标题
     */
    public DownloadDBBean getTitleInFinishByVid(int albumId, int vid) {
        synchronized (context) {
            Cursor cursor = null;
            try {
                DownloadDBBean mDownloadDBBean = null;
                cursor = context.getContentResolver().query(
                        LetvContentProvider.URI_WORLDCUPTRACE,
                        null,
                        DatabaseConstant.WorldCupTrace.Field.ALBUM_ID + "=? AND "
                                + DatabaseConstant.WorldCupTrace.Field.EPISODE_ID + "=? AND "
                                + DatabaseConstant.WorldCupTrace.Field.FINISH + "=?",
                                new String[] { albumId + "", vid + "", "4" }, null);
                
                if (cursor.moveToFirst()) {
                    mDownloadDBBean = createDownloadDBBean(cursor);
                }
                return mDownloadDBBean;
            } finally {
                LetvTools.closeCursor(cursor);
            }
        }
    }

    /**
     * 是否已经下载完成
     * 
     * @param episodeId
     * @return
     */
    public boolean isInFinish(String episodeId) {
        Cursor cursor = null;
        try {
            boolean isIn = false;

            cursor = context.getContentResolver().query(
                    LetvContentProvider.URI_WORLDCUPTRACE,
                    null,
                    DatabaseConstant.WorldCupTrace.Field.EPISODE_ID + "=? AND "
                            + DatabaseConstant.WorldCupTrace.Field.FINISH + "=?",
                    new String[] { episodeId, "4" }, null);

            return cursor.getCount() > 0;
        } finally {
            LetvTools.closeCursor(cursor);
        }
    }

    public void delete(int episodeId) {
        context.getContentResolver().delete(LetvContentProvider.URI_WORLDCUPTRACE,
                DatabaseConstant.WorldCupTrace.Field.EPISODE_ID + "=?",
                new String[] { episodeId + "" });
        //LocationDownloadTraceManager.updataLocationTrace(context);
    }

    /**
     * 下载完成更新
     * 
     * @param episodeId
     * @param totalSize
     * @return
     */
    public boolean finish(int episodeId, long totalSize) {
        try {
            ContentValues cv = new ContentValues();
            cv.put(DatabaseConstant.WorldCupTrace.Field.TOTAL_SIZE, totalSize);
            cv.put(DatabaseConstant.WorldCupTrace.Field.LENGTH, totalSize);
            cv.put(DatabaseConstant.WorldCupTrace.Field.FINISH, "4");
            context.getContentResolver().update(LetvContentProvider.URI_WORLDCUPTRACE, cv,
                    DatabaseConstant.WorldCupTrace.Field.EPISODE_ID + "=?",
                    new String[] { episodeId + "" });
//          LetvFunction.updateDownLoadRate();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据episodeId 更新下载大小
     * 
     * @param episodeId
     *            视频ID
     * @param totalSize
     *            总大小
     * @param downLoadSize
     *            已下载大小
     * @return
     */
    public boolean updateDownloadSize(String episodeId, long totalSize, long downLoadSize,
            int status) {
        try {
            ContentValues cv = new ContentValues();
            LogInfo.log("debug_tag", "status=" + status + "  updateDownloadSize episodeId ="
                    + episodeId + "  totalSize=" + totalSize + "--downLoadSize=" + downLoadSize);
            cv.put(DatabaseConstant.WorldCupTrace.Field.TOTAL_SIZE, totalSize);
            cv.put(DatabaseConstant.WorldCupTrace.Field.LENGTH, downLoadSize);
            cv.put(DatabaseConstant.WorldCupTrace.Field.FINISH, status);
            context.getContentResolver().update(LetvContentProvider.URI_WORLDCUPTRACE, cv,
                    DatabaseConstant.WorldCupTrace.Field.EPISODE_ID + "=?",
                    new String[] { episodeId });
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据aid 获取下载列表
     * 
     * @param albumId
     * @return
     */
    public List<DownloadDBBean> getAllDownloadInfoWithAid(long albumId) {
        Cursor cursor = null;
        List<DownloadDBBean> list = new ArrayList<DownloadDBBean>();
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_WORLDCUPTRACE,
                    null, DatabaseConstant.WorldCupTrace.Field.ALBUM_ID + "=?",
                    new String[] { albumId + "" },
                    DatabaseConstant.WorldCupTrace.Field.TIMESTAMP + " ASC");
            while (cursor.moveToNext()) {
                list.add(createDownloadDBBean(cursor));
            }
            return list;
        } finally {
            LetvTools.closeCursor(cursor);
        }
    }
    /**
     * 根据专辑ID 判断是否存在记录
     * @param albumId
     * @return
     */
    public boolean hasOldVersionItem(long albumId) {
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_WORLDCUPTRACE,
                    null, DatabaseConstant.WorldCupTrace.Field.ALBUM_ID + "=?",
                    new String[] { albumId + "" }, null);
            boolean isNew = false;
            while (cursor.moveToNext()) {
                if(cursor.getInt(cursor.getColumnIndex(DatabaseConstant.DownloadTrace.Field.IS_NEW)) == 0){
                    isNew = true;
                    break;
                }
            }
            return isNew;
        } finally {
            LetvTools.closeCursor(cursor);
        }
    }

    private DownloadDBBean createDownloadDBBean(Cursor cursor) {
        if (cursor == null) {
            return null;
        }

        DownloadDBBean mDownloadDBBean = new DownloadDBBean();
        try {
            mDownloadDBBean.setVid(cursor.getInt(cursor
                    .getColumnIndex(DatabaseConstant.WorldCupTrace.Field.EPISODE_ID)));
            mDownloadDBBean.setAid(cursor.getInt(cursor
                    .getColumnIndex(DatabaseConstant.WorldCupTrace.Field.ALBUM_ID)));
            mDownloadDBBean.setIcon(cursor.getString(cursor
                    .getColumnIndex(DatabaseConstant.WorldCupTrace.Field.ICON)));
            mDownloadDBBean.setType(cursor.getInt(cursor
                    .getColumnIndex(DatabaseConstant.WorldCupTrace.Field.TYPE)));
            mDownloadDBBean.setOrd(cursor.getInt(cursor
                    .getColumnIndex(DatabaseConstant.WorldCupTrace.Field.ORDER)));
            mDownloadDBBean.setCid(cursor.getInt(cursor
                    .getColumnIndex(DatabaseConstant.WorldCupTrace.Field.CID)));
            mDownloadDBBean.setEpisodetitle(cursor.getString(cursor
                    .getColumnIndex(DatabaseConstant.WorldCupTrace.Field.EPISODE_TITLE)));
            mDownloadDBBean.setEpisodeIcon(cursor.getString(cursor
                    .getColumnIndex(DatabaseConstant.WorldCupTrace.Field.EPISODE_ICON)));
            mDownloadDBBean.setAlbumtitle(cursor.getString(cursor
                    .getColumnIndex(DatabaseConstant.WorldCupTrace.Field.ALBUM_TITLE)));
            mDownloadDBBean.setTotalsize(cursor.getLong(cursor
                    .getColumnIndex(DatabaseConstant.WorldCupTrace.Field.TOTAL_SIZE)));
            mDownloadDBBean.setFinish(cursor.getInt(cursor
                    .getColumnIndex(DatabaseConstant.WorldCupTrace.Field.FINISH)));
            mDownloadDBBean.setTimestamp(cursor.getLong(cursor
                    .getColumnIndex(DatabaseConstant.WorldCupTrace.Field.TIMESTAMP)));
            mDownloadDBBean.setLength(cursor.getLong(cursor
                    .getColumnIndex(DatabaseConstant.WorldCupTrace.Field.LENGTH)));
            mDownloadDBBean.setIsHd(cursor.getInt(cursor
                    .getColumnIndex(DatabaseConstant.WorldCupTrace.Field.ISHD)));
            mDownloadDBBean.setBtime(cursor.getLong(cursor
                    .getColumnIndex(DatabaseConstant.WorldCupTrace.Field.B_TIME)));
            mDownloadDBBean.setEtime(cursor.getLong(cursor
                    .getColumnIndex(DatabaseConstant.WorldCupTrace.Field.E_TIME)));
            mDownloadDBBean.setFilePath(cursor.getString(cursor
                    .getColumnIndex(DatabaseConstant.WorldCupTrace.Field.FILE_PATH)));
        }catch(Exception e) {

            e.printStackTrace();
        }
        return mDownloadDBBean;
    }
}

